//
//  ConfirmBuyBookViewController.swift
//  BookStore2.0
//
//  Created by hw on 2022/6/1.
//

import UIKit

class ConfirmBuyBookViewController: UIViewController {

    @IBOutlet weak var BookNum: UILabel!
    
    @IBOutlet weak var BookNumStepper: UIStepper!
    
    @IBOutlet weak var confirmbookimg: UIImageView!
    
    var bookcopy=BookCopy()
    
    var Flag:Bool=false//加入购物车还是购买的标志
    
    override func viewDidLoad() {
        super.viewDidLoad()
        BookNumStepper.value=1
        bookcopy.amount=(Int)(BookNumStepper.value)
        BookNum.text="\(bookcopy.amount)"
        confirmbookimg.image=DB1.imgSet[bookcopy.id]
        // Do any additional setup after loading the view.
    }
    
    @IBAction func changeBookNum(_ sender: Any) {
        bookcopy.amount=(Int)(BookNumStepper.value)
        BookNum.text="\(bookcopy.amount)"
    }//更改买书数量
    
    @IBAction func ConfirmToBuy(_ sender: Any) {
        let num:Int=ShoppingCart.sharedinstance.ifAlreadyExists(id:bookcopy.id)
        var message:String="已加入购物车！"
        if Flag==false {
            message="已加入购物车！"
            if num == -1 {
                ShoppingCart.sharedinstance.addBookCopy(bookcopy: bookcopy)
                ShoppingCart.sharedinstance.updateBookCopiesData()
            }
            else{ ShoppingCart.sharedinstance.cartContents[num].amount+=bookcopy.amount
            }
            
        }
        else {
            message="购入完成！"
            let totalnum=bookcopy.amount
            let totalprice=bookcopy.eachprice*Float(totalnum)
            let time=Date()
            let order=Order(booknumSum: totalnum, moneySum: totalprice, ordertime: time)
            let result=DB1.insertOrder(order: order)
            let ID=(result![0]["max(rowid)"] as! NSNumber).intValue
            DB1.insertOrderItem(bookcopy: bookcopy, orderid: ID)
        }
        
        let p=UIAlertController(title:"操作成功",message:message,preferredStyle:.alert)
        p.addAction(UIAlertAction(title:"确定",style:.default,handler:{
            (
                act:UIAlertAction)in
        }))
        present(p,animated:false,completion:nil)
            }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
